<?php

namespace bc\wx;

use bc\util\Util;
use bc\service\wx\WechatAccessTokenService;
use bc\ar\MActiveRecord;

class Auth
{
	
	public $accessToken;
	public function __construct($appid, $secret)
	{
		
		$serivce = new WechatAccessTokenService();
		$accessToken = $serivce->getAccessToken();
		
		
		//通过一个api接口来校验access_token的正确实用性
		if($accessToken != null)
		{
			$url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token='.$accessToken;
			$result = Util::httpGet($url);
			$arr = json_decode($result, true);
			
			if(!$arr['ip_list'])
			{
				$accessToken = null;
			}
		}
		
		if ($accessToken == null)
		{
			// 去服务器拿去access_token
			$wechat = new Wechat ();
			$wechat->rootUrl;
			$url = $wechat->rootUrl . AppConst::WX_TOKEN_URL;
			$params ['grant_type'] = 'client_credential';
			$params ['appid'] = $appid;
			$params ['secret'] = $secret;
			
			$rs = json_decode(Util::httpGet ( $url, $params ), true);
			
			if($rs['access_token'] && $rs['expires_in'])
			{
				//写入数据库
				$serivce = new WechatAccessTokenService();
				$serivce->add(['access_token' => $rs['access_token'], 'create_time' => time()]);
				$this->accessToken = $rs['access_token'];
				
				
				//暂时用ecshop表的时间更新进去
				$updateSql = 'update wxch_config set access_token ="' . $rs['access_token'] . '" ,dateline = ' . time();
				$dao  = new MActiveRecord();
				$dao->getDb()->createCommand($updateSql)->execute();
				//end
			}
			
		}
		else 
		{
			$this->accessToken = $accessToken;
		}
	}
}

